"""
操作日志接口
"""
import re

from app.libs.redprint import RedPrint
from app.db.models.audits import Audit
from flask import jsonify
from flask import g
from app.api.v2.common import param_input, query_page_data
from app.validators.audit import ResultAudit


api = RedPrint('audit')


@api.route('/audit-result', methods=['GET'])
@param_input(ResultAudit, skip_defaults=False)
def audit_result(query):
    """资产列表"""
    q = {'uid': str(g.audit_uid)}

    createTime = []
    if query.get('affects') is not None:
        q['affects'] = {'$regex': re.escape(query['affects'])}
    if query.get('startTime'):
        start_time = {'createTime': {'$gte': query['startTime']}}
        createTime.append(start_time)
    if query.get('endTime'):
        end_time = {'createTime': {'$lt': query['endTime']}}
        createTime.append(end_time)
    if createTime:
        q['$and'] = createTime

    page, count = query['page'], query['count']
    sort = ['-id']

    results, count = query_page_data(Audit.objects, q, None, page, count, sort)
    return jsonify({'data': {'results': results, 'count': count}})
